package com.kiyuumirai.moviesever.service.impl;


import com.kiyuumirai.moviesever.service.TicketService;
import com.kiyuumirai.utils.enums.CodeEnum;
import com.kiyuumirai.utils.exception.ExpectedException;
import com.kiyuumirai.utils.model.dos.MovieDO;
import com.kiyuumirai.utils.model.dos.TicketDO;
import com.kiyuumirai.utils.model.dto.TicketDTO;
import com.kiyuumirai.moviesever.util.TicketIdGenerator;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author MirAi
 * @description 
 * @date 2020/11/30 16:45
 */
@Service
public class TicketServiceImpl implements TicketService {

    /** 电影存量 */
    private static Map<String, MovieDO> map = new HashMap<>();

    static {

        MovieDO t1 = new MovieDO(1, "joker", 50.0, 10);
        MovieDO t2 = new MovieDO(2, "navi", 40.0, 20);
        MovieDO t3 = new MovieDO(3, "skull", 30.0, 30);
        MovieDO t4 = new MovieDO(4, "queen", 20.0, 40);

        map.put("joker", t1);
        map.put("navi", t2);
        map.put("skull", t3);
        map.put("queen", t4);
    }

    @Override
    public TicketDO buy(TicketDTO ticketDTO) {

        Integer number = ticketDTO.getNumber();
        MovieDO movieDO = map.get(ticketDTO.getMovieName());

        TicketDO ticketDO = new TicketDO();

        synchronized (this) {

            if (movieDO == null) {
                throw new ExpectedException(CodeEnum.NO_SUCH_MOVIE);
            }

            if (movieDO.getMovieRemain() < number) {
                throw new ExpectedException(CodeEnum.NOT_ENOUGH_TICKET);
            }

            movieDO.setMovieRemain(movieDO.getMovieRemain() - number);

            ticketDO.setTicketId(TicketIdGenerator.generateTicketId());
            ticketDO.setTicketTotalPrice(movieDO.getMoviePrice() * number);
        }

        return ticketDO;
    }
}
